<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="text" placeholder="请输入内容">

    <button>发送请求</button>

    <!-- 显示结果 -->
    <div class="box"></div>

    <!-- websocket在浏览器端如何使用 -->
    <script>
        let input = document.getElementsByTagName('input')[0]
        let button = document.getElementsByTagName('button')[0]
        let div = document.getElementsByTagName('div')[0]
        // 常见webSocket 对象
        const socket = new WebSocket('ws://localhost:3000')

        // 2.监听socket服务 当webSocket 服务链接成功的时候就会触发
        socket.addEventListener('open', function() {
            div.innerHTML = '链接成功了！'
        })

        // 3.主动给websockt 发送信息
        button.addEventListener('click', function() {
            let value = input.value
            socket.send(value)
            input.value = ''
        })

        // 4.接收websocket的数据
        socket.addEventListener('message', function(event) {
            console.log(event.data)
            var db = `<div>${event.data}</div>`
            div.insertAdjacentHTML('beforeend', db)
        })

        // 5.服务断开
        socket.addEventListener('close', function() {
            div.innerHTML = '链接断开'
        })
    </script>
</body>
</html>